import base64
import os
from openai import OpenAI

# 图片二进制转base64字符串
def image_bytes_to_base64(image_bytes):
    try:
        return base64.b64encode(image_bytes).decode('utf-8')
    except Exception as e:
        print(f"图片转base64时出错: {e}")
        return None

# 读取图片文件为二进制
def read_image_bytes(image_path):
    try:
        with open(image_path, "rb") as image_file:
            return image_file.read()
    except Exception as e:
        print(f"读取图片时出错: {e}")
        return None

# 封装API交互为方法
# 新增 audio_bytes 可选参数，支持音频输入

def ask_image_question(user_question, image_bytes, audio_bytes=None, audio_format='mp3'):
    base64_image = image_bytes_to_base64(image_bytes) if image_bytes else None
    base64_audio = None
    if audio_bytes:
        try:
            base64_audio = base64.b64encode(audio_bytes).decode('utf-8')
        except Exception as e:
            print(f"音频转base64时出错: {e}")
            return None
    if not (user_question or base64_image or base64_audio):
        print("必须至少提供文字、图片或音频中的一种")
        return None
    client = OpenAI(
        base_url='https://ms-ens-35786fe7-e309.api-inference.modelscope.cn/v1',
        api_key='89990c70-6d06-456b-9002-4cdfe1134c2d',
    )
    # 构建消息内容
    content = []
    if user_question:
        content.append({
            'type': 'text',
            'text': user_question
        })
    if base64_image:
        content.append({
            'type': 'image_url',
            'image_url': {
                'url': f'data:image/png;base64,{base64_image}'
            }
        })
    # 只有模型支持音频时才添加audio_url，这里直接注释掉audio_url部分，避免400错误
    # if base64_audio:
    #     content.append({
    #         'type': 'audio_url',
    #         'audio_url': {
    #             'url': f'data:audio/{audio_format};base64,{base64_audio}'
    #         }
    #     })
    response = client.chat.completions.create(
        model='Qwen/Qwen2-VL-7B-Instruct',
        messages=[
            {
                'role': 'user',
                'content': content
            }
        ],
        max_tokens=1000,
        stream=True
    )
    result = ''
    for chunk in response:
        if chunk.choices[0].delta.content:
            result += chunk.choices[0].delta.content
    return result

# 示例用法
if __name__ == "__main__":
    image_path = "image2.png"
    if not os.path.exists(image_path):
        print(f"错误：找不到图片文件 {image_path}")
        exit(1)
    image_bytes = read_image_bytes(image_path)
    if not image_bytes:
        exit(1)
    user_question = "请详细描述这张图片的内容，并且请你分析人物看起来像是哪一部动漫的主角呢？"
    print(f"图片读取成功，大小: {len(image_bytes)} 字节")
    result = ask_image_question(user_question, image_bytes)
    print("AI分析结果：", result)
